import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  baseURL: process.env.VUE_APP_BASE_API, // 基地址
  timeout: 5000 // request timeout
})

// 配置请求拦截器
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${getToken()}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 判断是不是blob
    if (response.data instanceof Blob) {
      return response.data // 返回了Blob对象
    }
    // 3.1结构数据
    const { data, message, success } = response.data
    // 3.2判断:请求成功且业务成功 / 请求成功但业务失败
    if (success) {
      return data
    } else {
      Message.error(message)
      return Promise.reject(new Error(message))
    }
  },
  async error => {
    // 3.3处理token过期
    if (error.response.status === 401) {
      Message.error('登录过期了~')
      // 清除token
      await store.dispatch('user/logout')
      // 跳转到登录页
      router.replace('/login')
    } else {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }

    return Promise.reject(error)
  }

)

export default service
